package su.samcom.calc.service;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import su.samcom.calc.model.dao.CountryDao;
import su.samcom.calc.model.dao.LocationDao;
import su.samcom.calc.model.entity.Country;
import su.samcom.calc.model.entity.Location;
import su.samcom.calc.service.record.Converter;
import su.samcom.calc.service.record.LocationRecord;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Владислав on 31.12.13.
 */
@Service
@Transactional
public class LocationServiceBean implements LocationService {

    @Autowired
    CountryDao countryDao;
    @Autowired
    LocationDao locationDao;

    @Override
    public Location getById(Long id) {
        return locationDao.getById(id);
    }

    @Override
    public List<Country> getCountries() {
        return countryDao.getAll();
    }

    @Override
    public List<LocationRecord> getLikeLocations(String locationName, Long countryId) {
        List<Location> locations = locationDao.getLikeLocations(locationName, countryId);
        List<LocationRecord> locationRecords = new ArrayList<LocationRecord>();
        for(Location location : locations){
            LocationRecord locationRecord = new LocationRecord();
            Converter.populate(locationRecord, location);
            locationRecords.add(locationRecord);
        }
        return locationRecords;
    }

    @Override
    public Location getLocation(String locationName, Long countryId) {
        if(countryId == null || StringUtils.isBlank(locationName)){
            return null;
        }
        List<Location> locations = locationDao.getLocations(locationName, countryId);
        if(locations.size() > 0){
            return locations.get(0);
        }
        return null;
    }

}
